import _toPropertyKey from "@babel/runtime/helpers/esm/toPropertyKey";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isNil from "lodash/isNil";
var _excluded = ["_status"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _class;

/**
 * AssignMember
 * @date 2019-08-14
 */
import React from 'react';
import uuid from 'uuid/v4';
import { Modal } from 'antd';
import { Bind } from 'lodash-decorators';
import intl from 'utils/intl';
import notification from 'utils/notification';
import { parseParameters, delItemsToPagination, addItemsToPagination, getResponse, getEditTableData } from 'utils/utils';
import SearchForm from "./SearchForm";
import EditDataTable from "./EditDataTable";
/**
 * TODO: 每个角色 的唯一key 都使用 uuid 生成, 如果之后做了校验 可以使用 id
 * 由于 用户 id 作为 主键, 防止冲突, 使用使用mockId 作为主键
 * @type {string}
 */

var rowKey = '_mockId';
var AssignMember = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(AssignMember, _React$Component);

  var _super = _createSuper(AssignMember);

  function AssignMember() {
    var _this;

    _classCallCheck(this, AssignMember);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.searchFormRef = React.createRef();
    _this.state = {
      dataSource: [],
      pagination: {}
    };
    return _this;
  }

  _createClass(AssignMember, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props$roleDatas = this.props.roleDatasource,
          roleDatasource = _this$props$roleDatas === void 0 ? {} : _this$props$roleDatas;

      if (roleDatasource && !_isNil(roleDatasource.id)) {
        this.handleSearch();
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var prevRoleDatasource = prevProps.roleDatasource;
      var _this$props = this.props,
          roleDatasource = _this$props.roleDatasource,
          visible = _this$props.visible;

      if (visible && roleDatasource && !_isNil(roleDatasource.id)) {
        if ((prevRoleDatasource && prevRoleDatasource.id) !== roleDatasource.id) {
          this.handleSearch(undefined, !prevProps.visible && this.props.visible);
        }
      }
    }
  }, {
    key: "reload",
    value: function () {
      var _reload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var cachePagination;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                cachePagination = this.state.cachePagination;
                this.handleSearch(cachePagination);

              case 2:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function reload() {
        return _reload.apply(this, arguments);
      }

      return reload;
    }()
  }, {
    key: "handleSearch",
    value: function () {
      var _handleSearch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pagination, reOpen) {
        var _this$props2, handleFetchData, _this$props2$roleData, roleDatasource, params, res;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (reOpen) {
                  this.setState({
                    dataSource: [],
                    pagination: {},
                    cachePagination: {}
                  });
                } else {
                  this.setState({
                    cachePagination: pagination
                  });
                }

                _this$props2 = this.props, handleFetchData = _this$props2.handleFetchData, _this$props2$roleData = _this$props2.roleDatasource, roleDatasource = _this$props2$roleData === void 0 ? {} : _this$props2$roleData;
                params = this.searchFormRef.current ? this.searchFormRef.current.props.form.getFieldsValue() : {};
                _context2.next = 5;
                return handleFetchData(parseParameters(_objectSpread(_objectSpread({}, params), pagination)));

              case 5:
                res = _context2.sent;

                if (res) {
                  this.setState(_objectSpread(_objectSpread({}, res), {}, {
                    dataSource: res.dataSource.map(function (item) {
                      return _objectSpread(_objectSpread({}, item), {}, _defineProperty({
                        roleId: roleDatasource.id
                      }, rowKey, uuid()));
                    })
                  }));
                }

              case 7:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function handleSearch(_x, _x2) {
        return _handleSearch.apply(this, arguments);
      }

      return handleSearch;
    }() // SearchForm

  }, {
    key: "handleSearchFormAction",
    value: function () {
      var _handleSearchFormAction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return this.handleSearch();

              case 2:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function handleSearchFormAction() {
        return _handleSearchFormAction.apply(this, arguments);
      }

      return handleSearchFormAction;
    }() // EditDataTable

  }, {
    key: "handleTableChange",
    value: function () {
      var _handleTableChange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(page, filter, sorter) {
        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return this.handleSearch({
                  page: page,
                  sort: sorter
                });

              case 2:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function handleTableChange(_x3, _x4, _x5) {
        return _handleTableChange.apply(this, arguments);
      }

      return handleTableChange;
    }()
  }, {
    key: "handleTableAdd",
    value: function handleTableAdd() {
      var _newUser;

      var _this$props3 = this.props,
          _this$props3$resource = _this$props3.resourceLevel,
          resourceLevel = _this$props3$resource === void 0 ? [] : _this$props3$resource,
          _this$props3$roleData = _this$props3.roleDatasource,
          roleDatasource = _this$props3$roleData === void 0 ? {} : _this$props3$roleData;
      var _this$state = this.state,
          _this$state$dataSourc = _this$state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc,
          pagination = _this$state.pagination;
      var resourceLevelMap = {};
      resourceLevel.forEach(function (item) {
        resourceLevelMap[item.value] = item.meaning;
      });
      var newUser = (_newUser = {}, _defineProperty(_newUser, rowKey, uuid()), _defineProperty(_newUser, "isCreate", true), _defineProperty(_newUser, "_status", 'create'), _defineProperty(_newUser, "roleId", roleDatasource.id), _newUser); // if (roleDatasource.level === 'site') {
      //   newUser.assignLevel = 'organization';
      //   newUser.assignLevelMeaning = resourceLevelMap.orginization;
      //   newUser.assignLevelValue = roleDatasource.tenantId;
      //   newUser.assignLevelValueMeaning = roleDatasource.tenantName;
      // }
      // 分配 用户 默认分配 租户 层级

      newUser.assignLevel = 'organization';
      newUser.assignLevelMeaning = resourceLevelMap.orginization;
      newUser.assignLevelValue = roleDatasource.tenantId;
      newUser.assignLevelValueMeaning = roleDatasource.tenantName;
      this.setState({
        dataSource: [newUser].concat(_toConsumableArray(dataSource)),
        pagination: addItemsToPagination(1, dataSource.length, pagination)
      });
    }
  }, {
    key: "handleTableDelete",
    value: function () {
      var _handleTableDelete = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(deleteRows) {
        var _this2 = this;

        var backDeleteRows, onDeleteMember, res, responseRes, _this$state$dataSourc2, dataSource, noDeleteEditData;

        return _regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                backDeleteRows = [];
                deleteRows.forEach(function (record) {
                  if (!record.isCreate) {
                    var _ = record._status,
                        deleteRecord = _objectWithoutProperties(record, _excluded);

                    backDeleteRows.push(deleteRecord);
                  }
                });

                if (!(backDeleteRows.length !== 0)) {
                  _context5.next = 13;
                  break;
                }

                onDeleteMember = this.props.onDeleteMember;
                _context5.next = 6;
                return onDeleteMember(backDeleteRows.map(function (memberRole) {
                  return {
                    memberType: 'user',
                    memberId: memberRole.id,
                    roleId: memberRole.roleId
                  };
                }));

              case 6:
                res = _context5.sent;
                responseRes = getResponse(res);

                if (!responseRes) {
                  _context5.next = 12;
                  break;
                }

                notification.success();
                _context5.next = 13;
                break;

              case 12:
                return _context5.abrupt("return");

              case 13:
                _this$state$dataSourc2 = this.state.dataSource, dataSource = _this$state$dataSourc2 === void 0 ? [] : _this$state$dataSourc2;
                noDeleteEditData = dataSource.filter(function (item) {
                  return item._status && !deleteRows.some(function (record) {
                    return record[rowKey] === item[rowKey];
                  });
                });

                if (noDeleteEditData.length !== 0) {
                  Modal.confirm({
                    title: intl.get('ciam.roleManagement.view,message.title.isRefresh').d('有未保存的数据, 是否刷新'),
                    onOk: function onOk() {
                      _this2.reload();
                    },
                    onCancel: function onCancel() {
                      var pagination = _this2.props.pagination;

                      _this2.setState({
                        dataSource: dataSource.filter(function (item) {
                          return !deleteRows.some(function (record) {
                            return record[rowKey] === item[rowKey];
                          });
                        }),
                        pagination: delItemsToPagination(deleteRows.length, dataSource.length, pagination)
                      });
                    }
                  });
                } else {
                  this.reload();
                }

              case 16:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function handleTableDelete(_x6) {
        return _handleTableDelete.apply(this, arguments);
      }

      return handleTableDelete;
    }() // Modal

  }, {
    key: "handleOk",
    value: function handleOk() {
      var _this3 = this;

      var dataSource = this.state.dataSource;
      var editDataSource = dataSource.filter(function (item) {
        return item._status;
      });
      var validateDataSource = getEditTableData(editDataSource); // 由于控制了 确认按钮, 所以 editDataSource 一定优质

      if (validateDataSource.length === editDataSource.length) {
        // 数据校验成功
        var handleSave = this.props.handleSave;
        handleSave(validateDataSource.map(function (item) {
          var _ = item[rowKey],
              isCreate = item.isCreate,
              _status = item._status,
              id = item.id,
              newItem = _objectWithoutProperties(item, [rowKey, "isCreate", "_status", "id"].map(_toPropertyKey));

          newItem.memberId = id;
          return newItem;
        }), false, function () {
          notification.success(); // 成功后关闭 模态框

          _this3.handleClose();
        });
      }
    }
  }, {
    key: "handleClose",
    value: function () {
      var _handleClose = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        var close;
        return _regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                close = this.props.close;
                this.searchFormRef.current.props.form.resetFields();
                close();

              case 3:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function handleClose() {
        return _handleClose.apply(this, arguments);
      }

      return handleClose;
    }()
  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          _this$props4$visible = _this$props4.visible,
          visible = _this$props4$visible === void 0 ? false : _this$props4$visible,
          title = _this$props4.title,
          _this$props4$processi = _this$props4.processing,
          processing = _this$props4$processi === void 0 ? {} : _this$props4$processi,
          _this$props4$roleData = _this$props4.roleDatasource,
          roleDatasource = _this$props4$roleData === void 0 ? {} : _this$props4$roleData,
          tenantRoleLevel = _this$props4.tenantRoleLevel,
          path = _this$props4.path;
      var _this$state2 = this.state,
          _this$state2$dataSour = _this$state2.dataSource,
          dataSource = _this$state2$dataSour === void 0 ? [] : _this$state2$dataSour,
          pagination = _this$state2.pagination;
      return /*#__PURE__*/React.createElement(Modal, {
        width: 700,
        wrapClassName: "ant-modal-sidebar-right",
        transitionName: "move-right",
        visible: visible,
        title: title,
        onCancel: this.handleClose,
        onOk: this.handleOk,
        confirmLoading: processing.save,
        cancelButtonProps: {
          disabled: processing.save || processing.delete
        },
        okButtonProps: {
          disabled: dataSource.filter(function (record) {
            return record._status;
          }).length === 0 || processing.delete || processing.query
        }
      }, /*#__PURE__*/React.createElement(SearchForm, {
        wrappedComponentRef: this.searchFormRef,
        onSearch: this.handleSearchFormAction
      }), /*#__PURE__*/React.createElement(EditDataTable, {
        path: path,
        tenantRoleLevel: tenantRoleLevel,
        role: roleDatasource,
        dataSource: dataSource,
        pagination: pagination,
        onChange: this.handleTableChange,
        onTableAdd: this.handleTableAdd,
        onTableDelete: this.handleTableDelete,
        deleteLoading: processing.delete,
        queryLoading: processing.query,
        saveLoading: processing.save
      }));
    }
  }]);

  return AssignMember;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "handleSearchFormAction", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "handleSearchFormAction"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleTableChange", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleTableChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleTableAdd", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleTableAdd"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleTableDelete", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "handleTableDelete"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleOk", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "handleOk"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleClose", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "handleClose"), _class.prototype)), _class));
export { AssignMember as default };